package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.example.myapplication.Adapter.MsgAdapter;
import com.example.myapplication.Bean.Msg;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ChatAcvicity extends AppCompatActivity {
    private ListView chatlv;
    private TextView chattext;
    private EditText sendedit;
    private Button sendbtn;
    int sendid, receiveid;
    //int sendid,receiveid ;//发送id和接受id
    String receivename;
    List<Msg> msgList = new ArrayList<>();
    //    List<String>dataList =new ArrayList<>();//实例化
    MsgAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat_acvicity);
        initData();
        initView();
        setListener();
    }

    private void initData() {//获取初始的数据, 从数据库中取出
        SharedPreferences sp = getSharedPreferences("userinfo", MODE_PRIVATE);
        sendid = sp.getInt("myid", -1);
        receiveid = sp.getInt("friend", -1);
        receivename = sp.getString("friendname", "");
        for (Msg m : LitePal.findAll(Msg.class)) {
            /*我发给李四的消息    李四发给我的消息*/
            boolean a = sendid == m.getSend_id() && receiveid == m.getReceive_id();
            boolean b = sendid == m.getReceive_id() && receiveid == m.getSend_id();
            if (a || b) {
                msgList.add(m);
            }
        }
    }

    private void setListener() {
        /*发送按钮   发送消息就是存储消息在数据库*/
        sendbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = sendedit.getText().toString().trim();  //获取输入框内容
                Msg m = new Msg(0, sendid, receiveid, content, new Date());
                m.save();
                msgList.add(m);
                sendedit.setText("");
//                更新数据
                adapter.notifyDataSetChanged();

            }
        });
    }

    private void initView() {
//        for (Msg m:msgList){
//            dataList.add(m.getContent());
        chatlv = findViewById(R.id.chatlv);
        chattext = findViewById(R.id.chattext);
        sendedit = findViewById(R.id.sendedit);
        sendbtn = findViewById(R.id.sendbtn);

//        聊天界面在与谁聊天   在与  receivename  消息接收者
        chattext.setText("正在与" + receivename + "聊天中");
        adapter = new MsgAdapter(ChatAcvicity.this,
                R.layout.msg_item, msgList);
        chatlv.setAdapter(adapter);

    }
}
